package com.ljfresh.customer.utils.udesk;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.ljfresh.customer.utils.AliyunOss;
import com.ljfresh.customer.utils.FileUtils;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;

import java.io.*;


/**
 * @Author zzx
 */
public class UDeskUploadUtil {
    private static Logger logger = LoggerFactory.getLogger(FileUtils.class);

    static final String success = "success";
    //static final String result = "result";
    static final String fileName = "filename";

    // 最大文件大小
    private static long maxSize = 500000000;

    // 定义允许上传的文件扩展名
    private static final Map<String, String> extMap = new HashMap<String, String>();

    static {
        // 其中images,flashs,medias,files,对应文件夹名称,对应dirName
        // key文件夹名称
        // value该文件夹内可以上传文件的后缀名
        extMap.put("images", "gif,GIF,jpg,JPG,jpeg,JPEG,png,PNG,bmp,BMP");
        extMap.put("flashs", "swf,SWF,flv,FLV");
        extMap.put("medias", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,SWF,FLV,MP3,WAV,WMA,WMV,MID,AVI,MPG,ASF,RM,RMVB");
        extMap.put("files", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2,DOC,DOCX,XLS,XLSX,PPT,HTM,HTML,TXT,ZIP,RAR,GZ,BZ2");
        extMap.put("sensitive", "txt,TXT");
    }

    /**
     * 云服务器 上传文件   不重名文件
     *
     * @param myFile
     * @throws IOException
     * @throws NullPointerException
     */
    public static void UDeskUpload(MultipartFile myFile, HttpServletRequest request) throws IOException, NullPointerException {

        String result="";
        try{

        // 服务器的域名
        URL url = new URL(UDeskConst.TICKETS_UPLOAD_FILE_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 设置为POST情
        conn.setRequestMethod("POST");
        // 发送POST请求必须设置如下两行
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        // 设置请求头参数
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Content-Type", "application/octet-stream");

        OutputStream out = new DataOutputStream(conn.getOutputStream());

        // 上传文件

        StringBuilder sb = new StringBuilder();

        // 将参数头的数据写入到输出流中
        out.write(sb.toString().getBytes());

        // 数据输入流,用于读取文件数据
        DataInputStream in = new DataInputStream(myFile.getInputStream());
        byte[] bufferOut = new byte[1024*20];
        int bytes = 0;
        // 每次读8KB数据,并且将文件数据写入到输出流中
        while ((bytes = in.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }

        in.close();


        out.flush();
        out.close();

        // 定义BufferedReader输入流来读取URL的响应
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            result += line; //这里读取的是上边url对应的上传文件接口的返回值，读取出来后，然后接着返回到前端，实现接口中调用接口的方式
        }
    } catch (Exception e) {
        System.out.println("发送POST请求出现异常！" + e);
        e.printStackTrace();
    }
		System.out.println(result);
		//return  RespEntity.success(result);
}




    /**
     * 文件大小转换为字符串格式
     *
     * @param size 文件大小(单位B)
     * @return
     */
    public static String convertFileSize(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;

        if (size >= gb) {
            return String.format("%.1f GB", (float) size / gb);
        } else if (size >= mb) {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        } else if (size >= kb) {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        } else
            return String.format("%d B", size);
    }





    private byte[] readInputStream(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while ((len = inputStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }


}
